package jp.isisredirect.DreamWaverFirst;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DreamWaverStore {
	private static final String TAG = "DreamWaverStore";

	private DBOpenHelper m_helper;

	private SQLiteDatabase m_db;
	private static final String TBL_NAME = "DWStore";

	public DreamWaverStore(Context context) {
		m_helper = DBOpenHelper.getInstance(context);
		//open();
		if (m_helper == null) {
			Log.d(TAG, "DreamWaverStore m_helper null" );
		}
	}

	public void open() {
		if (m_helper != null)
			m_db = m_helper.getWritableDatabase();
		else
			m_db = null;
	}

	public void close() {
		m_db.close();
		m_db = null;
	}

	public void add(DreamWaverStoreData data) {
		if (m_db != null) {
			ContentValues val = new ContentValues();

			val.put("title", data.title);
			val.put("date", data.date);
			val.put("filepath", data.filepath);
			m_db.insert(TBL_NAME, null, val);
		}

	}
	
	public void delete(int id) {
		if (m_db != null) {
			m_db.delete(TBL_NAME, "_id=?", new String[] { Integer.toString(id) });
		}
	}

	
	public void update(DreamWaverStoreData data) {
		if (m_db != null) {
			ContentValues val = new ContentValues();

			val.put("title", data.title);
			val.put("date", data.date);
			val.put("filepath", data.filepath);
			m_db.update(TBL_NAME, val, "_id=?", new String[] { Integer.toString(data.id) });
		}
	}

	public DreamWaverStoreData[] loadAll() {
		int i;
		Cursor c;
		DreamWaverStoreData[] entries = null;

		if (m_db == null)
			return null;

		c = m_db.query(TBL_NAME, new String[] { "_id", "title", "date",
				"filepath" }, null, null, null, null, null);
		if (c != null) {
			int numRows = c.getCount();

			c.moveToFirst();

			entries = new DreamWaverStoreData[numRows];
			for (i = 0; i < numRows; i++) {
				entries[i] = new DreamWaverStoreData();
			}
			if (entries != null) {
				for (i = 0; i < numRows; i++) {
					entries[i].id = c.getInt(0);
					entries[i].title = c.getString(1);
					entries[i].date = c.getString(2);
					entries[i].filepath = c.getString(3);
					c.moveToNext();
				}
			}
			c.close();
		}
		return entries;
	}
}
